package com.medium.house.utils;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import java.nio.charset.Charset;
import java.util.*;

/**
 * @author wang.yu
 * Created by Milton on 2015/8/26 at 20:38.
 */
public class StringUtil
{
	
	private static  String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    /**
     * 为一个URL地址增加参数, 会自动判断是否使用'?'号连接
     *
     * @param url    链接
     * @param nvpairs 参数集合
     * @return 编码之后的带参数链接
     */
    public static String appendParametersToURL(String url, List<NameValuePair> nvpairs, String encoding) {
        if (url == null) {url = "";}
        if (nvpairs == null || nvpairs.size() == 0) {return url;}
        String paramsStr = URLEncodedUtils.format(nvpairs, Charset.forName(encoding));
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        if (url.indexOf('?') == -1) {
            sb.append('?');
        }else {
            sb.append('&');
        }
        sb.append(paramsStr);
        return sb.toString();
    }

    /**
     * 合并一個字符串數組, 用預置的字符做分隔
     *
     * @param collection
     * @param separator
     * @return
     */
    public static String implode(Collection<String> collection, String separator) {
        if (collection == null) {
            return null;
        }
        if (collection.size() == 0) {
            return "";
        }

        StringBuffer sb = new StringBuffer();
        Iterator<String> iterator = collection.iterator();
        while (iterator.hasNext()) {
            sb.append(iterator.next());
            if (iterator.hasNext()) {sb.append(separator);}
        }
        return sb.toString();
    }

    /**
     * 合并一個字符串數組, 用預置的字符做分隔
     *
     * @param array
     * @param separator
     * @return
     */
    public static String implode(String[] array, String separator) {
        if (array == null) {
            return null;
        }
        if (array.length == 0) {
            return "";
        }
        if (array.length == 1) {
            return array[0];
        }

        StringBuffer sb = new StringBuffer();
        sb.append(array[0]);
        for (int i = 1; i < array.length; i++) {
            sb.append(separator);
            sb.append(array[i]);
        }
        return sb.toString();
    }
    
    
    public static String getRandomString(int length){
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
          int number=random.nextInt(62);
          sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 只保留字符串首尾字符，隐藏中间用X代替（两个字符时只显示第一个）
     * @param user_name
     * @return string 格式化后的姓名
     */
    public static String substr_cut(String user_name){
        String result = "";
        int  strLen = getStringlength(user_name);
        String firstStr = user_name.substring(0, 1);
        String lastStr = user_name.substring(user_name.length()-1);
        if(strLen == 2){
            result = firstStr + "X";
        }else if(strLen > 2){
            String midStr = "";
            for (int i=0;i<strLen-2;i++){
                midStr += "X";
            }
            result  = firstStr + midStr + lastStr;
        }else {
            result = user_name;
        }
        return result;
    }
    /**
     * 获取字符串的长度，如果有中文，则每个中文字符计为2位
     * @param value 指定的字符串
     * @return 字符串的长度
     */
    public static int getStringlength(String value) {
        int valueLength = 0;
        //String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
           // if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
               // valueLength += 2;
          ///  } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            //}
        }
        return valueLength;
    }

    public static void main(String args[]){
        String str = "你好好";
        System.out.println(getStringlength(str));
        System.out.println(str.substring(0, 1));
        System.out.println(str.substring(str.length()-1));
        System.out.println(substr_cut(str));
    }

    public static void main2(String[] args) {
        String url = "http://www.auo.com/i812.html";
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("te", "测试"));
        nvps.add(new BasicNameValuePair("a", "ei23832181023udkdj=/3i12381%U_ _+ 12j"));
        nvps.add(new BasicNameValuePair("bewe", "测试中文长一点"));
        nvps.add(new BasicNameValuePair("bdid", "@$%^&*()())"));

        System.out.println(appendParametersToURL(url, nvps, "UTF-8"));
        System.out.println(appendParametersToURL(url, nvps, "GBK"));
    }

    /**
     * 判断密码各个位的数字是否全都一致
     * @param numOrStr 指定的字符串
     * @return 一致返回true
     */
    public static boolean equalStr(String numOrStr){
        boolean flag = true;
        char str = numOrStr.charAt(0);
        for (int i = 0; i < numOrStr.length(); i++) {
            if (str != numOrStr.charAt(i)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    /**
     * 判断连续的数字--递增（如：123456）
     * @param numOrStr 指定的字符串
     * @return 连续数字返回true
     */
    public static boolean isAddNumeric(String numOrStr){
        boolean flag = true;//如果全是连续数字返回true
        boolean isNumeric = true;//如果全是数字返回true
        for (int i = 0; i < numOrStr.length(); i++) {
            if (!Character.isDigit(numOrStr.charAt(i))) {
                isNumeric = false;
                break;
            }
        }
        if (isNumeric) {//如果全是数字则执行是否连续数字判断
            for (int i = 0; i < numOrStr.length(); i++) {
                if (i > 0) {//判断如123456
                    int num = Integer.parseInt(numOrStr.charAt(i)+"");
                    int num_ = Integer.parseInt(numOrStr.charAt(i-1)+"")+1;
                    if (num != num_) {
                        flag = false;
                        break;
                    }
                }
            }
        } else {
            flag = false;
        }
        return flag;
    }

    /**
     * 判断连续的数字--递减（如：987654）
     * @param numOrStr 指定的字符串
     * @return 连续数字返回true
     */
    public static boolean isDeleteNumeric(String numOrStr){
        boolean flag = true;//如果全是连续数字返回true
        boolean isNumeric = true;//如果全是数字返回true
        for (int i = 0; i < numOrStr.length(); i++) {
            if (!Character.isDigit(numOrStr.charAt(i))) {
                isNumeric = false;
                break;
            }
        }
        if (isNumeric) {//如果全是数字则执行是否连续数字判断
            for (int i = 0; i < numOrStr.length(); i++) {
                if (i > 0) {//判断如654321
                    int num = Integer.parseInt(numOrStr.charAt(i)+"");
                    int num_ = Integer.parseInt(numOrStr.charAt(i-1)+"")-1;
                    if (num != num_) {
                        flag = false;
                        break;
                    }
                }
            }
        } else {
            flag = false;
        }
        return flag;
    }

}
